package cn.gbase.jiangsu.data.transfer.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import cn.gbase.jiangsu.data.transfer.bean.SmsLog;
import cn.gbase.jiangsu.data.transfer.common.Constants;
import cn.gbase.jiangsu.data.transfer.service.ProductSortTreeNodeService;
import cn.gbase.jiangsu.data.transfer.service.SystemService;

public class SMSUtil {

	
	/**
	 * 合肥的短信接口.
	 * 
	 * @param Mobile
	 * @param Content
	 * @param send_time
	 * @return
	 * @throws MalformedURLException
	 * @throws UnsupportedEncodingException
	 */
	public static int sendSMS(String mobile, String content, String send_time,String corp,String pwd,int type,Dao dao) {


		// 发送内容
		String send_content = null;
		try {
			send_content = URLEncoder.encode(content.replaceAll("<br/>", " "),
					"GBK");
		} catch (UnsupportedEncodingException e1) {
		}

		// 发送
		URL url = null;
		try {
			url = new URL("http://www.106551.com:81/ws/BatchSend.aspx?CorpID="
					+ corp + "&Pwd=" + pwd + "&Mobile=" + mobile
					+ "&Content=" + send_content + "&Cell=&SendTime="
					+ send_time);
		} catch (MalformedURLException e1) {

		}
		BufferedReader in = null;
		int inputLine = 0;
		try {
			System.out.println("开始发送短信，手机号码为 ：" + mobile);
			System.out.println("内容 ：" + content);
			in = new BufferedReader(new InputStreamReader(url.openStream()));
			inputLine = new Integer(in.readLine()).intValue();
		} catch (Exception e) {
			System.out.println("网络异常,发送短信失败！");
			inputLine = -999;
		}

		String resultMsg = SMSUtil.getResultMsg(inputLine);
		// 写Log
		SmsLog log = new SmsLog();
		log.setSmsType(type);
		log.setMobile(mobile);
		log.setCreateTime(new Date());
		log.setIp(CommonUtil.getRemoteIp());
		log.setContent(content);
		log.setResultCode(inputLine);
		log.setResultMsg(resultMsg);
		dao.insert(log);
		System.out.println("结束发送短信返回值：  " + inputLine);
		return inputLine;
	}

	/**
	 * 取得Code对应的消息文字.
	 * 
	 * @param resultCode
	 * @return
	 */
	public static String getResultMsg(int resultCode) {
		switch (resultCode) {
		case 1:
		case 0:
			return "发送成功。";
		case -1:
			return "账号未注册。";
		case -2:
			return "其他错误。";
		case -3:
			return "帐号或密码错误。";
		case -4:
			return "一次提交信息不能超过600个手机号码。";
		case -5:
			return "余额不足，请先充值。";
		case -6:
			return "定时发送时间不是有效的时间格式。";
		case -8:
			return "发送内容需在3到250字之间。";
		case -9:
			return "发送号码为空。";
		default:
			return "未知错误。";
		}
	}
}
